<template>
  <div ref="container" class="h-screen w-full flex flex-col">
    <header style="min-height: 56px" class="h-14 px-4 flex items-center shadow">
      <div class="h-full flex flex-col justify-center">
        <p class="text-base text-center">WEB铺码DEMO</p>
        <p class="mt-1 text-xs text-center">V{{ version }}</p>
      </div>
    </header>
    <div class="flex-1 flex flex-col justify-around pb-12">
      <div class="flex justify-center">
        <el-button
          class="h-36 text-base rounded-lg border-dashed border-2"
          v-for="i in buttonList"
          :key="i.name"
          @click="onClickButton(i.name)"
          >{{ i.name }}
        </el-button>
      </div>
      <div class="flex justify-center">
        <div
          v-if="projectList.length !== 0"
          class="w-96 h-96 p-2 border rounded space-y-2 shadow overflow-y-auto"
        >
          <div class="flex items-center justify-between">
            <div>项目列表({{ projectList.length }})</div>
            <el-button @click="deleteAllProject">删除所有项目</el-button>
          </div>
          <div
            class="w-full p-2 relative cursor-pointer border"
            v-for="i in projectList"
            :key="i"
            @click="openProject(i)"
          >
            <div>项目名称：{{ i }}</div>
            <i
              class="el-icon-close absolute top-1 right-1"
              @click.stop="deleteProject(i)"
            ></i>
          </div>
        </div>
      </div>
    </div>
    <div
      class="
        fixed
        bottom-0
        left-0
        w-full
        h-10
        pb-2
        bg-white
        text-xs text-center
      "
    >
      <div>
        <a
          class="text-indigo-600"
          href="https://www.tqltech.com/"
          target="_blank"
          >深圳腾千里科技有限公司</a
        >版权所有
      </div>
      <div>copyright@2022</div>
    </div>
    <create-local-sperad-project-dialog
      ref="createLocalSperadProjectDialog"
    ></create-local-sperad-project-dialog>
    <create-global-sperad-project-dialog
      ref="createGlobalSperadProjectDialog"
    ></create-global-sperad-project-dialog>
  </div>
</template>

<script>
import { version } from "../../package.json";
import {
  loading,
  checkProjectFileType,
  getProjectFileContent,
  generateProject,
} from "@/common/utils";
import {
  getStoreList,
  deleteStore,
  deleteDatabase,
  getStoreExist,
} from "@/common/indexedDB";
import CreateLocalSperadProjectDialog from "@/components/CreateLocalSperadProjectDialog.vue";
import CreateGlobalSperadProjectDialog from "@/components/CreateGlobalSperadProjectDialog.vue";
export default {
  components: {
    CreateLocalSperadProjectDialog,
    CreateGlobalSperadProjectDialog,
  },
  data() {
    return {
      version,
      // 项目列表
      projectList: [],
      buttonList: [
        { name: "新建全局铺码项目", image: "" },
        { name: "新建局部铺码项目", image: "" },
      ],
    };
  },
  methods: {
    // 点击按钮触发
    onClickButton(name) {
      switch (name) {
        case this.buttonList[0].name:
          this.$refs.createGlobalSperadProjectDialog.open();
          break;
        case this.buttonList[1].name:
          this.$refs.createLocalSperadProjectDialog.open();
          break;
        case this.buttonList[2].name:
          break;
      }
    },
    // 打开项目
    openProject(projectName) {
      this.$router.push(`/local/${projectName}`);
    },
    // 删除项目
    deleteProject(projectName) {
      this.$confirm("此操作将永久删除该项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteStore(projectName);
        })
        .catch(() => {
          return;
        });
    },
    // 删除所有项目
    deleteAllProject() {
      this.$confirm("此操作将永久删除所有项目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteDatabase();
        })
        .catch(() => {
          return;
        });
    },
    // $API
    async deleteDatabase() {
      const result = await loading({
        text: "删除仓库中...",
        fn: async () => await deleteDatabase(),
      });
      console.log("删除仓库", result);
      const { code, msg, data } = result;
      if (code === 200) {
        this.$message.success("删除成功");
        this.getStoreList();
      } else {
        this.$message.error(msg);
      }
    },
    // 获取仓库列表
    async getStoreList() {
      const result = await loading({
        text: "项目列表加载中...",
        fn: async () => await getStoreList(),
      });
      console.log("项目列表", result);
      const { code, msg, data } = result;
      if (code === 200) {
        this.projectList = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 删除仓库
    async deleteStore(storeName) {
      const result = await loading({
        text: "删除仓库中...",
        fn: async () => await deleteStore(storeName),
      });
      const { code, msg, data } = result;
      console.log("删除仓库", result);
      if (code === 200) {
        this.$message.success("删除成功");
        this.getStoreList();
      } else {
        this.$message.error(data);
      }
    },
    // $监听拖拽事件
    listenerDrop(element) {
      // 监听拖拽事件
      element.addEventListener("dragover", (e) => e.preventDefault());
      element.addEventListener("drop", async (e) => {
        // 阻止浏览器默认行为
        e.preventDefault();
        const file = e.dataTransfer.files[0];
        // 检查项目文件类型
        if (!checkProjectFileType(file)) return;
        // 读取项目文件内容
        const readResult = await getProjectFileContent(file);
        if (readResult.code !== 200) {
          return this.$message.error("项目文件格式错误");
        }
        // 项目文件内容
        const project = readResult.data;
        // 判断仓库中是否存在同名项目
        const exist = await getStoreExist(project.name);
        if (exist.data) {
          return this.$message.error("已存在该名称项目！");
        }
        const result = await generateProject(project);
        if (result.code !== 200) {
          return this.$message.error(result.msg);
        }
        this.$message.success("项目导入成功！");
        this.getStoreList();
      });
    },
  },
  mounted() {
    this.getStoreList();
    this.listenerDrop(this.$refs.container);
  },
};
</script>
